import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import './ProjectsPage.css'; // 复用项目页面的样式
import CreateProjectGroupModal from '../modals/CreateProjectGroupModal';
import EditProjectGroupModal from '../modals/EditProjectGroupModal';
import { projectGroupApi } from '../../services/api';

// 日期格式化函数
const formatDateTime = (isoString) => {
  if (!isoString) return '';
  
  try {
    const date = new Date(isoString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
  } catch (error) {
    console.error('日期格式化失败:', error);
    return isoString; // 如果格式化失败，返回原始字符串
  }
};

const ProjectGroupsPage = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [projectGroups, setProjectGroups] = useState([]);
  
  
  // 分页状态
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(10);
  const [total, setTotal] = useState(0);
  
  // 弹框状态
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentProjectGroup, setCurrentProjectGroup] = useState(null);

  // 加载项目组数据
  const loadProjectGroups = async () => {
    setLoading(true);
    try {
      const response = await projectGroupApi.getProjectGroups(page, size);
      if (response.code === 200 && response.data) {
        setProjectGroups(response.data.records || []);
        setTotal(response.data.total || 0);
      } else {
        console.error('加载项目组失败:', response.message);
      }
    } catch (error) {
      console.error('加载项目组异常:', error);
    } finally {
      setLoading(false);
    }
  };

  // 首次加载和搜索条件变化时重新加载数据
  useEffect(() => {
    loadProjectGroups();
  }, [page, size]);





  // 处理创建项目组
  const handleCreateProjectGroup = async (projectGroup) => {
    try {
      console.log('创建项目组:', projectGroup);
      const response = await projectGroupApi.addProjectGroup(projectGroup);
      if (response.code === 200 && response.data) {
        alert('创建项目组成功');
        setIsCreateModalOpen(false);
        loadProjectGroups();
      } else {
        alert(`创建项目组失败: ${response.message}`);
      }
    } catch (error) {
      console.error('创建项目组异常:', error);
      alert(`创建项目组异常: ${error.message}`);
    }
  };

  // 处理编辑项目组
  const handleEditProjectGroup = async (projectGroup) => {
    try {
      const response = await projectGroupApi.updateProjectGroup(projectGroup);
      if (response.code === 200 && response.data) {
        alert('更新项目组成功');
        setIsEditModalOpen(false);
        loadProjectGroups();
      } else {
        alert(`更新项目组失败: ${response.message}`);
      }
    } catch (error) {
      console.error('更新项目组异常:', error);
      alert(`更新项目组异常: ${error.message}`);
    }
  };

  // 处理删除项目组
  const handleDeleteProjectGroup = async (id) => {
    if (!window.confirm('确定要删除此项目组吗？')) return;
    
    try {
      const response = await projectGroupApi.deleteProjectGroup(id);
      if (response.code === 200 && response.data) {
        alert('删除项目组成功');
        loadProjectGroups();
      } else {
        alert(`删除项目组失败: ${response.message}`);
      }
    } catch (error) {
      console.error('删除项目组异常:', error);
      alert(`删除项目组异常: ${error.message}`);
    }
  };

  // 打开编辑模态框
  const openEditModal = (projectGroup) => {
    setCurrentProjectGroup(projectGroup);
    setIsEditModalOpen(true);
  };

  // 处理分页
  const handlePageChange = (newPage) => {
    setPage(newPage);
  };

  return (
    <div className="projects-page">
      <div className="page-header">
        <h1>项目组管理</h1>
        <button onClick={() => setIsCreateModalOpen(true)} className="btn-primary">
          <span className="plus-icon">+</span> 创建项目组
        </button>
      </div>

      <div className="table-container">
        <table className="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>项目组名称</th>
              <th>描述</th>
              <th>创建时间</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan="6" className="loading-cell">加载中...</td>
              </tr>
            ) : projectGroups.length === 0 ? (
              <tr>
                <td colSpan="6" className="no-data-cell">暂无数据</td>
              </tr>
            ) : (
              projectGroups.map(group => (
                <tr key={group.id}>
                  <td>{group.id}</td>
                  <td>{group.name}</td>
                  <td>{group.description}</td>
                  <td>{formatDateTime(group.createdAt)}</td>
                  <td>{formatDateTime(group.updatedAt)}</td>
                  <td>
                    <button 
                      className="action-button edit" 
                      onClick={() => openEditModal(group)}
                    >
                      编辑
                    </button>
                    <button 
                      className="action-button delete" 
                      onClick={() => handleDeleteProjectGroup(group.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="pagination">
        <button 
          disabled={page === 1} 
          onClick={() => handlePageChange(page - 1)}
        >
          上一页
        </button>
        <span>第 {page} 页 / 共 {Math.ceil(total / size)} 页</span>
        <button 
          disabled={page >= Math.ceil(total / size)} 
          onClick={() => handlePageChange(page + 1)}
        >
          下一页
        </button>
      </div>

      {/* 创建项目组模态框 */}
      <CreateProjectGroupModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSubmit={handleCreateProjectGroup}
      />

      {/* 编辑项目组模态框 */}
      {currentProjectGroup && (
        <EditProjectGroupModal
          isOpen={isEditModalOpen}
          onClose={() => setIsEditModalOpen(false)}
          onSubmit={handleEditProjectGroup}
          projectGroup={currentProjectGroup}
        />
      )}
    </div>
  );
};

export default ProjectGroupsPage;
